package com.mis.pos.controller;

import com.mis.pos.common.utils.ApiResponse;
import com.mis.pos.common.utils.PageUtil;
import com.mis.pos.dto.ItemDTO;
import com.mis.pos.dto.ItemNumberDTO;
import com.mis.pos.entity.InventoryEntity;
import com.mis.pos.entity.ItemEntity;
import com.mis.pos.entity.SaleEntity;
import com.mis.pos.form.IsSaledForm;
import com.mis.pos.form.ItemForm;
import com.mis.pos.form.ItemSearchForm;
import com.mis.pos.service.InventoryService;
import com.mis.pos.service.TypeService;
import com.mis.pos.service.ItemService;
import com.mis.pos.service.SaleService;
import com.mis.pos.service.dsl.ItemSearchService;
import com.mis.pos.service.impl.ItemServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 商品查询控制类
 * @Author yuxiang
 * @CreatedDate 2019/11/7 17:12
 */
@RestController
@RequestMapping("/item")
public class ItemController {

    /**
     * 打印日志对象
     */
    private Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

    /**
     * 注入商品业务层service
     */
    @Autowired
    private ItemService itemService;
    @Autowired
    private ItemSearchService itemSearchService;

    /**
     * 注入订单业务层service
     */
    @Autowired
    private SaleService saleService;

    /**
     * 注入分类service
     */
    @Autowired
    private TypeService typeService;

    /**
     * 注入库存service
     */
    @Autowired
    private InventoryService inventoryService;

    /**
     * 商品查询
     * @param searchForm 查询表单
     * @param pageNumber 页数
     * @param pageSize 一页多少条
     * @return
     */
    @PostMapping("/searchItem")
    public ApiResponse searchItem(@RequestBody ItemSearchForm searchForm,
                                  @RequestParam(value = "pageNumber",defaultValue = "1")Integer pageNumber,
                                  @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        List<ItemDTO> dtos = new ArrayList<>();
        Map map  = new HashMap();
        Integer count  = 0;
        try {
             map = itemSearchService.searchByItemForm(searchForm, (pageNumber-1)*pageSize, pageSize);
            dtos = (List<ItemDTO>) map.get("dtos");
            count = Math.toIntExact((Long) map.get("count"));
        }catch (Exception e){
            logger.info("服务器出异常");
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出异常");
        }

        return PageUtil.pageManual(dtos,pageNumber,pageSize,count);
    }

    /**
     * 获取分类列表
     * @return
     */
    @GetMapping("/getClassList")
    @RequiresPermissions("item:getClassList")
    public ApiResponse getClassList(){
        List<String> list = new ArrayList<>();//分类列表
        try {
           list =  typeService.findAllClassName();
        }catch (Exception e){
            logger.info("获取分类列表出现问题");
            e.printStackTrace();
            return new ApiResponse(-1,"获取分类列表出现问题");
        }
        return  new ApiResponse(0,"获取分类列表成功",list);
    }

    /**
     * 一键生成订单
     * @param dtos 商品id和商品数量
     * @param isPayed 是否立即支付
     * @return
     */
    @PostMapping("/oneKeySale")
    public ApiResponse oneKeySale(@RequestBody List<ItemNumberDTO> dtos,
                                  @RequestParam(value = "count",defaultValue = "0.0") Double count,
                                  @RequestParam(defaultValue = "无",value = "description") String description,
                                  @RequestParam(value = "isPayed",defaultValue = "0")int isPayed){

        ApiResponse response = new ApiResponse();
        try {
            //1.创建一个订单
            if (dtos.size()!=0){
                SaleEntity saleEntity = new SaleEntity(count,description,isPayed);
                //2.更改库存
                for (ItemNumberDTO dto :
                        dtos) {
                    inventoryService.changeInventory(dto.getItemId(),dto.getNumber());
                }
                //3.订单和商品关联
                //商品ids
                if (saleService.save(saleEntity)==0){
                    saleService.saveSaleItem(dtos,saleEntity.getId());
                }else {
                    return new ApiResponse(-1,"服务器错误，生成订单失败");
                }
            }else {
                return new ApiResponse(-1,"未选择商品列表");
            }
            response.setEvent(0);
            response.setMsg("一键生成订单成功！");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误，生成订单失败");
        }

        return response;

    }

    /**
     * 添加商品
     * @param itemForm
     * @return
     */
    @PostMapping("/addItem")
    public ApiResponse addItem(@RequestBody ItemForm itemForm){

        ApiResponse<ItemEntity> apiResponse = new ApiResponse<>();
        ItemEntity entity;
        try {
            if (StringUtils.isNotEmpty(itemForm.getItemName())&&StringUtils.isNotBlank(itemForm.getItemName())){
                //商品名一定不为空
                entity = new ItemEntity(itemForm.getItemName(),itemForm.getPrice(),itemForm.getBrand(),1);
                itemService.save(entity);
            }else {
                return new ApiResponse(-1,"商品名为空");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出现错误");
        }
        apiResponse.setEvent(0);
        apiResponse.setObj(entity);
        apiResponse.setMsg("添加成功！");
        return apiResponse;

    }

    /**
     * 下架商品
     * @param isSaledForm 商品实体
     * @return
     */
    @PostMapping("/changeSaled")
    public ApiResponse changeItem(@RequestBody IsSaledForm isSaledForm){
        ApiResponse response = new ApiResponse();
        try {
            if (isSaledForm.getItemId()==null){
                return new ApiResponse(-1,"商品id为空");
            }
            //改变商品
            System.out.println(isSaledForm.toString());
            itemService.updateIsSaledById(isSaledForm.getItemId(),isSaledForm.getIsSaled());
            response.setMsg("改变商品状态成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出现错误");
        }
        return response;
    }

}
